<?php

namespace common\model;

use think\Hook;
use think\model\RelationModel;
use think\module\Module;

class SaasEntityModel extends RelationModel
{


    protected $connection = 'database.mysql_saas';
    protected $tableName = 'entity';
    // 自动验证
    protected $_validate = [
        ['name', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['name', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['code', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['code', '', '', self::EXISTS_VALIDATE, 'alphaDash'],
        ['project_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['module_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['status_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['entity_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['entity_module_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['start_time', '', '', self::EXISTS_VALIDATE, 'date'],
        ['end_time', '', '', self::EXISTS_VALIDATE, 'date'],
        ['duration', '0,8', '', self::EXISTS_VALIDATE, 'length'],
        ['estimate_hours', '0,20', '', self::EXISTS_VALIDATE, 'length'],
        ['cost_hours', '0,20', '', self::EXISTS_VALIDATE, 'length'],
        ['json', '', '', self::EXISTS_VALIDATE, 'array'],

        ['director_star', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'], // 导演关注
        ['key_shot', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'], // 关键镜头

    ];

    // 自动完成
    protected $_auto = [
        ['tenant_id', 'auto_fill_tenant_id', self::MODEL_INSERT, 'function'],
        ['project_id', 'auto_fill_project_id', self::MODEL_INSERT, 'function_with_data'],
        ['module_id', 'auto_fill_default_id', self::MODEL_INSERT, 'function_with_data'],
        ['entity_id', 'auto_fill_default_id', self::MODEL_INSERT, 'function_with_data'],
        ['entity_module_id', 'auto_fill_default_id', self::MODEL_INSERT, 'function_with_data'],
        ['code', 'fillEntityCode', self::MODEL_INSERT, 'callback_with_data'],
        ['code', 'fillEntityCode', self::MODEL_UPDATE, 'callback_with_data'],
        ['start_time', 'strtotime', self::EXISTS_VALIDATE, 'function'],
        ['end_time', 'strtotime', self::EXISTS_VALIDATE, 'function'],
        ['plan_start_time', 'strtotime', self::EXISTS_VALIDATE, 'function'],
        ['plan_end_time', 'strtotime', self::EXISTS_VALIDATE, 'function'],
        ['json', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['created_by', 'fill_created_by', self::MODEL_INSERT, 'function'],
        ['created', 'time', self::MODEL_INSERT, 'function'],
        ['uuid', 'auto_fill_uuid', self::MODEL_INSERT, 'function_with_data'],
        ['description', 'fill_text_default_val', self::MODEL_INSERT, 'function']
    ];

    // 自动完成后验证
    protected $_validate_after_auto = [
        ['code', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['name,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'design'],
        ['name,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'asset'],
        ['name,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'level'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'episode'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id,initial_episode_code', '', '', self::MUST_VALIDATE, 'unique', '', 'sequence'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id,initial_episode_code,showings_number', '', '', self::MUST_VALIDATE, 'unique', '', 'shot'],
        ['code,tenant_id,project_id,module_id,initial_episode_code,showings_number', '', '', self::MUST_VALIDATE, 'unique', '', 'storyboard'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'todo'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'creative'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'design'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'color'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'dub_in'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'sound_mixing'],
        ['code,tenant_id,project_id,module_id,entity_id,entity_module_id', '', '', self::MUST_VALIDATE, 'unique', '', 'clip'],
    ];

    // 隐藏字段
    protected $hidden = ['json'];

    /**
     * 获取器：自定义字段
     * @param $value
     * @param $data
     * @return array|mixed
     */
    public function getJsonAttr($value, $data)
    {
        // 当前模块的自定义字段配置
        $currentModuleCode = empty(\request()->getModuleCode()) ? 'entity' : \request()->getModuleCode();
        $fieldDict = Module::$moduleDictData['field_index_by_code'][$currentModuleCode]['custom'];

        // 判断是否有值
        if (!empty($value)) {
            $jsonDictData = json_decode($value, true);
        } else {
            $jsonDictData = [];
        }

        // 把自定义值写入追加字段
        foreach ($fieldDict as $filed => $config) {
            if (array_key_exists($filed, $jsonDictData)) {
                $this->appendCustomField[$filed] = $jsonDictData[$filed];
            } else {
                // 没有值赋空值
                $this->appendCustomField[$filed] = "";
            }
        }

        return $jsonDictData;
    }


    /**
     * @inheritDoc
     */
    protected function autoValidation($data, $type, $validate = [])
    {
        $validate = $this->validateFilterByModuleCode($validate);
        if (empty($validate)) {
            return true;
        }
        return parent::autoValidation($data, $type, $validate);
    }

    /**
     * 筛选验证规则 多模块筛选
     * @param $validate
     * @return array
     */
    private function validateFilterByModuleCode($validate)
    {
        // todo 当前模块code获取优化
        $currentModuleCode = request()->getModuleCode();
        foreach ($validate as $key => $val) {
            $moduleCode = $val[6] ?? null;
            // 如果规则指定了需要验证的模块那么就移除条件
            if (!empty($moduleCode) && $currentModuleCode !== $moduleCode) {
                unset($validate[$key]);
            }
        }
        return $validate;
    }

    /**
     * 填充实体code
     * 概念,资产,关卡 如果更新了名称  code就会重新生成随机码
     * @param $data
     * @return bool|mixed|string
     * @throws \think\Exception
     */
    public function fillEntityCode($data)
    {
        $dontAllowRepeatGenerateModule = [
            'design', 'asset', 'level'
        ];

        // 数据里包含了code 就直接返回code
        if (!empty($data['code'])) {
            return $data['code'];
        }

        if (!empty($data['id'])) {
            // update
            $oldData = $this::query("select * from entity where id = {$data['id']}")[0];
            if (in_array(module_by_id($oldData['module_id'])['code'], $dontAllowRepeatGenerateModule)) {
                if (!empty($data['name']) && $data['name'] !== $oldData['name']) {
                    return generate_asset_code($data['name'], 6);
                } else {
                    return $oldData['code'];
                }
            }
        } else {
            // insert
            if (!empty($data['module_id']) && in_array(module_by_id($data['module_id'])['code'], $dontAllowRepeatGenerateModule)) {
                return generate_asset_code($data['name'], 6);
            }
        }
        return auto_fill_not_null_code($data, 'code');
    }

    /**
     * 获得模块唯一性验证规则
     * @param $moduleCode
     * @return false|string[]
     */
    public function getModuleUniqueValidation($moduleCode)
    {
        $default = [
            'code',
            'tenant_id',
            'project_id',
            'module_id',
            'entity_id',
            'entity_module_id',
        ];
        foreach ($this->_validate_after_auto as $v) {
            if (!empty($v['4']) && $v['4'] === 'unique') {
                if (!empty($v['6']) && $v['6'] === $moduleCode) {
                    return explode(',', $v[0]);

                } else {
                    $default = explode(',', $v[0]);
                }
            }
        }
        return $default;
    }
}
